﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;

namespace Import_Plugin
{
    public class ImportPluginUpdate: IPlugin 
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =(ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];

                int new_action = 0;
                if (entity.Attributes.Contains("new_action"))
                {
                    new_action = ((OptionSetValue)entity.Attributes["new_action"]).Value;
                }
                if (new_action != 100000001)
                {
                    //not an import
                    return;
                }


                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                Guid new_importsolutiontaskid = context.PrimaryEntityId;
                string fileName = "";
                byte[] fileBytes = getAttachedSolutionFile(new_importsolutiontaskid, service, ref fileName);


                if (entity.Attributes.Contains("new_filename"))
                {
                    entity.Attributes["new_filename"] = fileName;
                }
                else
                {
                    entity.Attributes.Add("new_filename", fileName);
                }


                ImportSolutionRequest impSolReq = new ImportSolutionRequest()
                {
                    CustomizationFile = fileBytes
                };
                Entity entpre = (Entity)context.PreEntityImages["Image"];
                int new_importtype = ((OptionSetValue)entpre.Attributes["new_importtype"]).Value;
                
                if (entity.Attributes.Contains("new_importtype"))
                {
                    new_importtype = ((OptionSetValue)entity.Attributes["new_importtype"]).Value;
                }
                
                if (new_importtype == 100000001)
                {
                    //Async import
                    ExecuteAsyncRequest req = new ExecuteAsyncRequest();
                    req.Request = impSolReq;
                    ExecuteAsyncResponse resp = (ExecuteAsyncResponse)service.Execute(req);
                    if (context.InputParameters.Contains("new_importjobid"))
                    {
                        entity.Attributes["new_importjobid"] = resp.AsyncJobId.ToString();
                    }
                    else
                    {
                        entity.Attributes.Add("new_importjobid", resp.AsyncJobId.ToString());
                    }
                }
                else
                {
                    //Sync import
                    try
                    {
                        service.Execute(impSolReq);
                    }
                    catch (System.Exception ex)
                    {
                        throw new InvalidPluginExecutionException(ex.StackTrace);
                    }
                }

            }
        }

        public byte[] getAttachedSolutionFile(Guid new_importsolutiontaskid, IOrganizationService service, ref string fileName)
        {

            string fetchXml = string.Format(@"<fetch version='1.0' mapping='logical' output-format='xml-platform'>
                                                    <entity name='annotation'>
                                                        <attribute name='filename' />
                                                        <attribute name='documentbody' />
                                                        <filter type='and'>
				                                            <condition attribute='objectid' 
                                                                operator='eq' value='{0}' />
                                                        </filter>
                                                    </entity>
                                                </fetch>", new_importsolutiontaskid.ToString());
            EntityCollection notes=service.RetrieveMultiple(new FetchExpression(fetchXml));
            if (notes.Entities.Count == 0)
            {
                return null;
            }
            Entity retrievedAnnotation = notes.Entities[0];
            fileName = retrievedAnnotation.Attributes["filename"].ToString();
            byte[] fileContent = Convert.FromBase64String(retrievedAnnotation.Attributes["documentbody"].ToString());

            return fileContent;
        }


    }
}
